﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Core.Infrastructure.CommandExtensions
{
    public class ItemsControlDragLeave
    {
        private static readonly DependencyProperty ItemsControlDragLeaveCommandBehaviorProperty = DependencyProperty.RegisterAttached(
            "ItemsControlDragLeaveCommandBehavior",
            typeof(ItemsControlDragLeaveCommandBehavior),
            typeof(ItemsControlDragLeave),
            null);

        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(ItemsControlDragLeave),
            new PropertyMetadata(OnSetCommandCallback));

        public static void SetCommand(ItemsControl itemsControl, ICommand command)
        {
            itemsControl.SetValue(CommandProperty, command);
        }

        public static ICommand GetCommand(ItemsControl itemsControl)
        {
            return itemsControl.GetValue(CommandProperty) as ICommand;
        }

        private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var itemsControl = dependencyObject as ItemsControl;
            if (itemsControl != null)
                GetOrCreateBehavior(itemsControl).Command = e.NewValue as ICommand;
        }

        private static ItemsControlDragLeaveCommandBehavior GetOrCreateBehavior(ItemsControl itemsControl)
        {
            var behavior = itemsControl.GetValue(ItemsControlDragLeaveCommandBehaviorProperty) as ItemsControlDragLeaveCommandBehavior;
            if (behavior == null)
            {
                behavior = new ItemsControlDragLeaveCommandBehavior(itemsControl);
                itemsControl.SetValue(ItemsControlDragLeaveCommandBehaviorProperty, behavior);
            }

            return behavior;
        }

    }
}
